package 竞赛.NO_451;

import java.util.Stack;

/**
 * TODO
 * 创建时间：2025-05-25 11:25
 */
public class Q4_移除相邻字符后字典序最小的字符串 {
    public static String lexicographicallySmallestString(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!stack.isEmpty()) {
                char top = stack.peek();
                if (Math.abs(c - top) == 1 || Math.abs(c - top) == 25) {
                    stack.pop();
                    if ((i + 1 < s.length() &&  top < s.charAt(i + 1)) || (i + 2 < s.length() &&  c < s.charAt(i + 2))) {
                        stack.push(top);
                        stack.push(c);
                    }
                    continue;
                }
            }
            stack.push(c);
        }
//        while (!stack.isEmpty() && stack.size() > 1) {
//            if (Math.abs(stack[stack.size()] - stack.peek()) == 1 || Math.abs(c - top) == 25) {
//        }
        StringBuilder ans = new StringBuilder();
        for (char c : stack) {
            ans.append(c);
        }
        return ans.toString();
    }
}
